package org.pidan.basic.multiThread;

import java.util.concurrent.locks.ReentrantLock;

/**
 * {@code @description}: ReentrantLock 实例
 * 非公平锁
 * 公平锁
 * <p>
 * {@code @author}: huangyuxin
 * {@code @date}: 2023-12-13
 */
public class ReentrantLockDemo2 {

    private static int num = 0;

    //创建非公平锁（默认为非公平）
//    private static ReentrantLock lock = new ReentrantLock(false);

    //公平锁
    //系统内部肯定需要维护一个有序队列，因此公平锁的实现成本比较高，性能相对于非公平锁来说相对低一些
    private static ReentrantLock lock = new ReentrantLock(true);


    public static class T1 extends Thread {

        public T1(String name) {
            super(name);
        }


        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                lock.lock();
                try {
                    System.out.println(this.getName() + "拿到锁");
                } finally {
                    lock.unlock();
                }
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        T1 t1 = new T1("1");
        T1 t2 = new T1("2");
        T1 t3 = new T1("3");

        t1.start();
        t2.start();
        t3.start();


        t1.join();
        t2.join();
        t3.join();

        System.out.println(ReentrantLockDemo2.num);
    }
}
